<template>
  <!-- v-loading是elementui提供的自定义指令 -->
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 组件重复了，封装复用 -->
        <TreeTools :tree-node="company" :is-root="true" class="header" @addDep="addDepFn" />
        <el-tree :data="depts" default-expand-all :props="defaultProps">
          <!-- data是传出来的每个节点的数据 -->
          <template v-slot="{ data }">
            <TreeTools :tree-node="data" @updateDeps="getDepartments" @addDep="addDepFn" @editDep="editDepFn" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- sync数据双向绑定 -->
    <AddDep
      ref="addDep"
      :visible.sync="addVisible"
      :current-node="currentNode"
      :origin-depts="originDepts"
      @updateDepartment="getDepartments"
    />
  </div>
</template>

<script>
import TreeTools from './components/TreeTools.vue'
import { getDepartments } from '@/api/department.js'
import { tranListToTreeData } from '@/utils/index'
import AddDep from '@/views/departments/components/AddDep.vue'
export default {
  components: { TreeTools, AddDep },
  data() {
    return {
      loading: false,
      company: { },
      // defaultProps是定义树解构里的属性名
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      depts: [],
      originDepts: [],
      addVisible: false,
      currentNode: {}
    }
  },

  created() {
    this.getDepartments()
  },

  methods: {
    async getDepartments() {
      try {
        this.loading = true
        const res = await getDepartments()
        // console.log(res)
        this.originDepts = res.depts
        this.depts = tranListToTreeData(res.depts, '')
        // 添加孩子节点，完善添加时重复验证
        this.company = { name: res.companyName, manager: '负责人', children: this.depts }
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    addDepFn(currentNode) {
      // console.log('增加部门')
      this.addVisible = true
      // treetools组件里的节点数据传给父组件，父组件接收后再传给addDep组件，这种状态叫做状态提升
      this.currentNode = currentNode
    },
    editDepFn(node) {
      // console.log(node)传过来的节点信息
      // 获取子组件实例里的数据，把treetools里的数据直接结构赋值给adddep
      this.addVisible = true
      this.$refs.addDep.formData = {
        ...node,
        children: ''// 这里的children会覆盖上面的children
      }
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 60px;
  font-size: 14px;
}
.header {
  height: 30px;
}
</style>
